/*
 * 任务添加/编辑
 * @Author: Wilbur
 * @Date: 2018-10-22 15:24:22
 * @Last Modified by: Wilbur
 * @Last Modified time: 2018-12-03 16:21:47
 */
<template>
    <div class="container task-editor-wrap">
        <el-form
            v-if="init"
            ref="mainform"
            :model="formData"
            label-position="right"
            status-icon
            :rules="formRule"
            label-width="90px"
            :disabled="false">
            <!-- 赞助商设置 -->
            <div class="form-unit">
                <div class="form-title">赞助商设置</div>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="hire_name"
                    label="赞助商:">
                    <el-input
                        placeholder="必填"
                        v-model="formData.hire_name"
                        size="small"
                        class="task-input"/>
                    <span style="display:inline-block;color:#999;margin-left:12px">*赞助商名称字数不超过15字</span>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="hire_logo"
                    label="赞助商Logo:">
                    <el-upload
                        class="avatar-uploader-customer"
                        action="https://jsonplaceholder.typicode.com/posts/"
                        :show-file-list="false"
                        :http-request="e=> {fnUploadImageOfCustomerLogo(e)}"
                        accept="image/*">
                        <img
                            v-if="formData.hire_logo"
                            :src="formData.hire_logo"
                            class="avatar">
                        <i
                            v-else
                            class="el-icon-plus avatar-uploader-icon"/>
                    </el-upload>
                    <span style="display:inline-block;color:#999;margin-left:12px">*只能上传jpg/png文件</span>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="monitor_say_content"
                    label="用户说:">
                    <el-input
                        placeholder="选填"
                        v-model="formData.monitor_say_content"
                        size="small"
                        class="task-input"/>
                    <span style="display:inline-block;color:#999;margin-left:12px"/>
                </el-form-item>
            </div>

            <div class="form-unit">
                <div class="form-title">任务设置</div>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="title"
                    label="任务名称:">
                    <el-input
                        placeholder="必填"
                        v-model="formData.title"
                        size="small"
                        class="task-input"/>
                    <span style="display:inline-block;color:#999;margin-left:12px">*标题字数不超过16字</span>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="image_url"
                    label="任务图片:">
                    <el-upload
                        class="upload-demo"
                        drag
                        action="https://jsonplaceholder.typicode.com/posts/"
                        :http-request="e=> {fnUploadImageOfTask(e)}"
                        :show-file-list="false"
                        accept="image/*">
                        <i
                            class="el-icon-upload"
                            v-if="formData.image_url == ''"/>
                        <div
                            v-if="formData.image_url == ''"
                            class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div
                            class="el-upload__tip"
                            slot="tip">banner大小：654px × 300px，只能上传jpg/png文件，且不超过500kb
                        </div>
                        <div
                            v-if="formData.image_url"
                            class="uploaded-image"
                            :style="'background-image: url('+formData.image_url+')'">
                        <!-- <el-button
                            type="danger"
                            class="icon-delete"
                            icon="el-icon-delete"
                            @click="formData.image_url = ''"
                            circle/> -->
                        </div>
                    </el-upload>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="type"
                    style="white-space: nowrap"
                    label="任务类型:">
                    <el-radio
                        :disabled="!!taskNo"
                        size="small"
                        v-model="formData.type"
                        :label="0">普通任务</el-radio>
                    <el-radio
                        :disabled="!!taskNo"
                        size="small"
                        v-model="formData.type"
                        :label="1">成长任务</el-radio>
                    <span style="display:inline-block;color:#999;margin-left:12px">*成长任务可提升用户等级</span>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="type"
                    style="white-space: nowrap"
                    label="任务类别:">
                    <el-radio
                        size="small"
                        v-model="formData.category"
                        :label="1">赞助类型</el-radio>
                    <el-radio
                        size="small"
                        v-model="formData.category"
                        :label="2">活动类型</el-radio>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="all_count"
                    label="任务数量:">
                    <el-input-number
                        v-model="formData.all_count"
                        controls-position="right"
                        size="small"
                        placeholder="必填"
                        :min="1" />
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="taskTime"
                    label="执行时间:">
                    <el-date-picker
                        v-model="formData.taskTime"
                        type="datetimerange"
                        range-separator="至"
                        size="small"
                        class="task-input"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间" />
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="intro"
                    label="任务介绍:">
                    <!-- <rich-text
                        v-model="formData.intro"
                        class="task-intro-input" /> -->
                    <ueditor
                        v-if="init"
                        ref="ueditor"
                        :default-value="formData.intro"/>

                </el-form-item>
            </div>
            <div class="form-unit">
                <div class="form-title">任务执行及奖励设置</div>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="level_limit"
                    label="人员限制:">
                    <el-select
                        v-model="formData.level_limit"
                        placeholder="请选择"
                        class="task-input"
                        size="small">
                        <el-option
                            v-for="item in limitOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                    </el-select>
                    <span style="display:inline-block;color:#999;margin-left:12px">*人员等级为任务最低门槛，所设等级及高等级人员均可领取</span>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="pre_task_nos"
                    label="前置任务:">
                    <el-select
                        class="task-input"
                        v-model="formData.pre_task_nos"
                        multiple
                        placeholder="无">
                        <el-option
                            v-for="item in preTaskList"
                            :key="item.task_no"
                            :label="item.title"
                            :value="item.task_no" />
                    </el-select>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="can_get_lottery_try_count"
                    style="white-space: nowrap"
                    label="抽奖机会:">
                    <el-radio
                        size="small"
                        v-model="formData.can_get_lottery_try_count"
                        :label="0">无</el-radio>
                    <el-radio
                        size="small"
                        v-model="formData.can_get_lottery_try_count"
                        :label="1">有</el-radio>
                    <span style="display:inline-block;color:#999;margin-left:12px">*完成任务后可赠送用户一次抽奖机会</span>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="award"
                    label="任务奖励:">
                    <el-cascader
                        class="task-input"
                        :options="awartOption"
                        v-model="formData.award"
                        @change="fnAwardChange"/>
                    <span style="display:inline-block;color:#999;margin-left:12px">*分级奖励不填写，则默认与LV0的奖励一致</span>
                </el-form-item>
                <!-- 统一积分 -->
                <el-form-item
                    v-if="formData.award[0] == 1 && formData.award[1] == 2"
                    class="task-form-item"
                    size="small"
                    prop="award_score"
                    label="">
                    <el-input-number
                        v-model="formData.award_score"
                        controls-position="right"
                        size="small"
                        placeholder="必填"
                        :min="0" />
                    <span>积分</span>
                </el-form-item>
                <!-- 统一现金 -->
                <el-form-item
                    v-if="formData.award[0] == 1 && formData.award[1] == 1"
                    class="task-form-item"
                    size="small"
                    prop="award_money"
                    label="">
                    <el-input-number
                        v-model="formData.award_money"
                        controls-position="right"
                        size="small"
                        placeholder="必填"
                        :min="0" />
                    <span>元</span>
                </el-form-item>
                <!-- 分级积分 -->
                <el-form-item
                    v-if="formData.award[0] == 2 && formData.award[1] == 2"
                    class="task-form-item"
                    size="small"
                    prop="award_score_for_level"
                    label="">
                    <el-table
                        border
                        :data="[awardScoreLevel]"
                        style="width: 800px">
                        <el-table-column
                            align="center"
                            label="人员等级">
                            <template slot-scope="scope">
                                奖励(积分)
                            </template>
                        </el-table-column>
                        <el-table-column
                            align="center"
                            v-for="lv in 11"
                            :key="lv"
                            :prop="'lv' + (lv-1)"
                            :label="'LV' + (lv-1)"
                            min-width="50">
                            <template slot-scope="scope">
                                <input
                                    type="Number"
                                    class="table-inner-input"
                                    v-model="scope.row['lv' + (lv-1)]"
                                    :disabled="false">
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
                <!-- 分级现金 -->
                <el-form-item
                    v-if="formData.award[0] == 2 && formData.award[1] == 1"
                    class="task-form-item"
                    size="small"
                    prop="award_money_for_level"
                    label="">
                    <el-table
                        border
                        :data="[awardMoneyLevel]"
                        style="width: 800px">
                        <el-table-column
                            align="center"
                            label="人员等级">
                            <template slot-scope="scope">
                                奖励(元)
                            </template>
                        </el-table-column>
                        <el-table-column
                            align="center"
                            v-for="lv in 11"
                            :key="lv"
                            :prop="'lv' + (lv-1)"
                            :label="'LV' + (lv-1)"
                            min-width="50">
                            <template slot-scope="scope">
                                <input
                                    type="Number"
                                    class="table-inner-input"
                                    v-model="scope.row['lv' + (lv-1)]"
                                    :disabled="false">
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </div>
            <div class="form-unit">
                <div class="form-title">任务反馈设置</div>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="statistic"
                    label="反馈统计:">
                    <!-- :disabled="!!taskNo" -->
                    <el-radio
                        size="small"
                        v-model="formData.statistic"
                        :label="1">统计</el-radio>
                    <!-- :disabled="!!taskNo" -->
                    <el-radio
                        size="small"
                        v-model="formData.statistic"
                        :label="0">不统计<span style="display:inline-block;color:#999;margin-left:12px">*针对反馈图片/文本的统计，如统计反馈朋友圈图片的评论数</span></el-radio>
                    <br>
                    <template v-if="formData.statistic == 1">
                        <!-- :disabled="!!taskNo" -->
                        <el-input-number
                            class="margin-top"
                            v-model="statisticSize"
                            controls-position="right"
                            size="small"
                            :min="0"
                            @change="fnChangeItem(statisticSize, formData.statistic_config, {title: ''})" />
                        <span>文本</span>
                        <div
                            class="input-width-delete"
                            v-for="(statisticItem, statisticIndex) in formData.statistic_config"
                            :key="statisticIndex">
                            <!-- :disabled="!!taskNo" -->
                            <el-input
                                placeholder="必填"
                                v-model="statisticItem.title"
                                size="small"
                                class="task-input" />
                            <!-- :disabled="!!taskNo" -->
                            <el-button
                                size="small"
                                @click="fndeleteItem(formData.statistic_config, statisticIndex, 'statisticSize')">删除</el-button>
                        </div>
                    </template>
                </el-form-item>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="submit_config"
                    label="反馈设置:">
                    <!-- :disabled="!!taskNo" -->
                    <el-checkbox
                        size="small"
                        v-model="formData.texts_help">文本</el-checkbox>
                    <!-- :disabled="!!taskNo" -->
                    <el-checkbox
                        size="small"
                        v-model="formData.images_help">图片<span style="display:inline-block;color:#999;margin-left:12px">*任务需要用户提交的反馈内容，如文本：手机号码、淘宝账号，图片：各种截图等</span></el-checkbox>
                    <br>
                    <template v-if="formData.texts_help">
                        <!-- :disabled="!!taskNo" -->
                        <el-input-number
                            class="margin-top"
                            v-model="textsHelpSize"
                            controls-position="right"
                            size="small"
                            :min="0"
                            @change="fnChangeItem(textsHelpSize, formData.submit_config.submit_texts_help, {desc: ''})" />
                        <span>文本</span>
                        <div
                            class="input-width-delete"
                            v-for="(textItem, textIndex) in formData.submit_config.submit_texts_help"
                            :key="textIndex">
                            <el-input
                                placeholder="必填"
                                v-model="textItem.desc"
                                size="small"
                                class="task-input" />
                            <!-- :disabled="!!taskNo" -->
                            <el-button
                                size="small"
                                @click="fndeleteItem(formData.submit_config.submit_texts_help, textIndex, 'textsHelpSize')">删除</el-button>
                        </div>
                    </template>
                    <template v-if="formData.images_help">
                        <!-- :disabled="!!taskNo" -->
                        <el-input-number
                            class="margin-top"
                            v-model="imagesHelpSize"
                            controls-position="right"
                            size="small"
                            :min="0"
                            @change="fnChangeItem(imagesHelpSize, formData.submit_config.submit_images_help, {desc: '',img_url: '', status: '', preview_url: ''})" />
                        <span>图片</span>
                        <div class="upload-list clearfix">
                            <div
                                class="pic-width-delete"
                                v-for="(imageItem, imageIndex) in formData.submit_config.submit_images_help"
                                :key="imageIndex">
                                <div class="pic-unit">
                                    <div class="pic-unit-index">{{ imageIndex+1 }}</div>
                                    <div class="pic-unit-detail">
                                        <div class="pic-unit-desc">
                                            <!-- :disabled="!!taskNo" -->
                                            <textarea
                                                placeholder="请输入内容"
                                                class="pic-unit-textarea"
                                                v-model="imageItem.desc"/>
                                        </div>
                                        <!-- :disabled="!!taskNo" -->
                                        <el-upload
                                            :multiple="true"
                                            class="edit-upload-wrapper pic-unit-img"
                                            action="https://jsonplaceholder.typicode.com/posts/"
                                            :http-request="e=> {fnUpload(e, imageItem)}"
                                            list-type="picture-card"
                                            accept="image/*"
                                            :show-file-list="false"
                                            :before-upload="file=>{fnBeforeUpload(file, imageItem)}"
                                            :on-error=" (err, file, fileList) => {fnUploadError(imageItem)}"
                                            :on-success="(resp, file, fileList) => {fnUploadSuccess(resp, file,imageItem)}"
                                            :on-change="(file, fileList) => { fnUploadChange(file, imageItem)}">
                                            <div
                                                v-if="imageItem.preview_url"
                                                class="pic-value"
                                                :style="'background-image: url('+imageItem.preview_url+')'">
                                                <div
                                                    class="loading"
                                                    v-if="imageItem.status == 'uploading'">
                                                    <i class="el-icon-loading"/>
                                                </div>
                                                <div
                                                    class="tip"
                                                    v-if="!taskNo">点击更换图片</div>
                                            </div>

                                            <div
                                                class="pic-value pic-empty"
                                                v-else>
                                                <div class="pic-empty-container">
                                                    <div class="pic-empty-plus">+</div>
                                                    <div class="pic-empty-desc">上传反馈示例图片</div>
                                                </div>
                                            </div>
                                        </el-upload>
                                    </div>
                                </div>
                                <!-- :disabled="!!taskNo" -->
                                <el-button
                                    size="small"
                                    @click="fndeleteItem(formData.submit_config.submit_images_help, imageIndex, 'imagesHelpSize')">删除</el-button>
                            </div>
                        </div>
                    </template>
                </el-form-item>
            </div>

            <div class="form-unit">
                <div class="form-title">投放设置</div>
                <el-form-item
                    class="task-form-item"
                    size="small"
                    prop="type"
                    style="white-space: nowrap"
                    label="投放人群:">
                    <el-radio
                        :disabled="!!taskNo"
                        size="small"
                        v-model="formData.class_limit"
                        :label="0">全部投放</el-radio>
                    <el-radio
                        :disabled="!!taskNo"
                        size="small"
                        v-model="formData.class_limit"
                        :label="1">精准投放</el-radio>
                    <span style="display:inline-block;color:#999;margin-left:12px">*精准投放会展示在班级任务大厅中。全部投放会在任务大厅中展示。</span>
                </el-form-item>
                <div class="operate-baar">
                    <el-popover
                        placement="top"
                        trigger="click">
                        <div
                            class="preview-image"
                            v-loading="false"
                            :style="'background-image: url('+`${baseUrl}/__local/common%5Cqrcode?content=${escape(mobileUrl + '/task-detail?id=' + taskNo)}&__ticket=${sessionTicket}`+')'" />
                        <el-button
                            slot="reference"
                            size="medium"
                            :disabled="!taskNo"
                            @click="fnShowPreview()">预览</el-button>
                    </el-popover>
                    <el-button
                        size="medium"
                        type="primary"
                        @click="fnSubmit()">提交</el-button>
                </div>
            </div>
        </el-form>
    </div>
</template>

<script>
// import richText from '@/components/common/rich-text';
import ueditor from '@/components/common/ueditor.vue';
export default {
    components: { ueditor },
    data() {
        var validateNumver = (rule, value, callback) => {
            if (!value) {
                if(value == 0) {
                    callback();
                }else{
                    callback(new Error(rule.message));
                }
            } else {
                if (value < 0) {
                    callback(new Error(rule.message));
                    return ;
                }
                callback();
            }
        };

        // 验证二位数组,且数组内元素不为空
        var validateArray = (rule, value, callback) => {
            if (!value) {
                callback(new Error(rule.message));
            } else {
                if (value.length < 2 || !value[0] || !value[1]) {
                    callback(new Error(rule.message));
                    return ;
                }
                callback();
            }
        };
        // 验证二位数组,且数组内元素不为空
        var validateAwardMoneyLevel = (rule, val, callback) => {
            let value = this.awardMoneyLevel;

            if (!value) {
                callback(new Error('请填写分级奖励金额'));
            } else {
                if (!value.lv0 || value.lv0 <= 0) {
                    callback(new Error('LV0奖励金额必填'));
                    return ;
                }
                callback();
            }
        };
        var validateAwardScoreLevel = (rule, val, callback) => {
            let value = this.awardScoreLevel;

            if (!value) {
                callback(new Error('请填写奖励积分'));
            } else {
                if (!value.lv0 || value.lv0 <= 0) {
                    callback(new Error('LV0奖励积分必填'));
                    return ;
                }
                callback();
            }
        };

        var validateStatistic = (rule, value, callback) => {
            if(this.formData.statistic == 1){
                if(this.statisticSize <= 0){
                    callback(new Error('至少添加一个统计项'));
                    return ;
                }else{
                    for(var i in this.formData.statistic_config){
                        if(!this.formData.statistic_config[i].title){
                            callback(new Error('统计项内容不能为空'));
                            return ;
                        }
                    }
                }
            }
            callback();
        };

        var validateSubmitConfig = (rule, value, callback) => {
            if(!this.formData.texts_help && !this.formData.images_help){
                callback(new Error('至少添加一个反馈项'));
                return ;
            }
            if(this.formData.texts_help){
                if(this.textsHelpSize <= 0){
                    callback(new Error('请至少添加一个文本反馈'));
                    return ;
                }else{
                    for(var i in this.formData.submit_config.submit_texts_help){
                        if(!this.formData.submit_config.submit_texts_help[i].desc){
                            callback(new Error('第'+(i*1+1)+'个文本反馈内容尚未填写'));
                            return ;
                        }
                    }
                }
            }
            if(this.formData.images_help){
                if(this.imagesHelpSize <= 0){
                    callback(new Error('请至少添加一个图片反馈'));
                    return ;
                }else{
                    for(var j in this.formData.submit_config.submit_images_help){
                        if(!this.formData.submit_config.submit_images_help[j].desc){
                            callback(new Error('第'+(j*1+1)+'个图片描述尚未填写'));
                            return ;
                        }
                        if(this.formData.submit_config.submit_images_help[j].status != 'success'){
                            callback(new Error('第'+(j*1+1)+'个图片尚未上传完毕'));
                            return ;
                        }
                        if(!this.formData.submit_config.submit_images_help[j].img_url){
                            callback(new Error('第'+(j*1+1)+'个图片尚未上传'));
                            return ;
                        }
                    }
                }
            }
            callback();
        };

        return {
            authResult: {},
            breadcrumbList: [
                {
                    title: "校园工作室管理",
                },
                {
                    title: "任务列表",
                    name: 'TaskList',
                },
                {
                    title: '添加任务'
                }
            ],
            taskNo: '',
            preTaskList: [],
            awartOption: [{
                label: '统一奖励',
                value: 1,
                children: [{
                    label: '现金',
                    value: 1,
                }, {
                    label: '积分',
                    value: 2,
                }]
            }, {
                label: '分级奖励',
                value: 2,
                children: [{
                    label: '现金',
                    value: 1,
                }, {
                    label: '积分',
                    value: 2,
                }]
            }],
            limitOptions: [{
                label: '不限制',
                value: 0,
            }, {
                label: 'LV1',
                value: 1,
            }, {
                label: 'LV2',
                value: 2,
            }, {
                label: 'LV3',
                value: 3,
            }, {
                label: 'LV4',
                value: 4,
            }, {
                label: 'LV5',
                value: 5,
            }, {
                label: 'LV6',
                value: 6,
            }, {
                label: 'LV7',
                value: 7,
            }, {
                label: 'LV8',
                value: 8,
            }, {
                label: 'LV9',
                value: 9,
            }, {
                label: 'LV10',
                value: 10,
            }],
            awardScoreLevel: {
                lv0: '',
                lv1: '',
                lv2: '',
                lv3: '',
                lv4: '',
                lv5: '',
                lv6: '',
                lv7: '',
                lv8: '',
                lv9: '',
                lv10: '',
            },
            awardMoneyLevel: {
                lv0: '',
                lv1: '',
                lv2: '',
                lv3: '',
                lv4: '',
                lv5: '',
                lv6: '',
                lv7: '',
                lv8: '',
                lv9: '',
                lv10: '',
            },
            // 统计字段数量
            statisticSize: 1,
            // 反馈文本数量
            textsHelpSize: 1,
            // 反馈图片数量
            imagesHelpSize: 1,
            // 预览链接
            previewUrl: '',
            formData: {
                "category": 1,
                "hire_logo": '',
                "image_url": '',
                "monitor_say_content": '',
                "class_limit": 0,
                "title": "",
                "type": 1,
                "all_count": '',
                taskTime: ['', ''],
                "start_time": '',
                "end_time": '',
                "intro": "",
                "level_limit": 0,
                "pre_task_nos": [],
                "can_get_lottery_try_count": 0,
                award: [1, 1],
                "award_score": 0,
                "award_money": 0,
                "award_score_for_level": {},
                "award_money_for_level": {},
                statistic: 0,
                "statistic_config": [
                    {
                        "title": ""
                    }
                ],
                texts_help: false,
                images_help: false,
                "submit_config": {
                    "submit_texts_help": [
                        {
                            "desc": ""
                        }
                    ],
                    // 接口获取原始数据
                    // "submit_images_help": [
                    //     {
                    //         "img_url": "string",
                    //         "desc": "img1"
                    //     }
                    // ]
                    // 经过处理的提交图片对象
                    "submit_images_help": [
                        {
                            status: 'success',//上传状态success/uploading
                            preview_url: '',//预览链接
                            "img_url": "",
                            "desc": ""
                        }
                    ]
                }
            },
            formRule: {
                hire_name: [
                    { required: true, message: '请输入赞助商名称', trigger: 'blur' },
                    { min: 1, max: 15, message: '长度在 1 到 15 个字', trigger: 'blur' }
                ],
                hire_logo: [
                    { required: true, message: '请输入赞助商Logo', trigger: 'change' }
                ],
                image_url: [
                    { required: true, message: '请输入任务展示图', trigger: 'change' }
                ],
                title: [
                    { required: true, message: '请输入任务名称', trigger: 'blur' },
                    { min: 1, max: 16, message: '长度在 1 到 16 个字', trigger: 'blur' }
                ],
                type: [
                    { required: true, message: '请选择任务类型', trigger: 'blur' }
                ],
                all_count: [
                    { required: true, message: '请填写任务数量', trigger: 'blur' },
                    { validator: validateNumver, message: '请填写任务数量', trigger: 'blur' }
                ],
                taskTime: [
                    { required: true, message: '请填写执行时间', trigger: 'blur' },
                    { validator: validateArray, message: '请填写正确的执行时间', trigger: 'blur' }
                ],
                intro: [
                    { required: true, message: '请填写任务介绍', trigger: 'blur' }
                ],
                award: [
                    { required: true, message: '请选择奖励', trigger: 'blur' },
                    { validator: validateArray, message: '请选择奖励', trigger: 'blur' }
                ],
                award_score: [
                    { required: true, message: '请填写奖励积分', trigger: 'blur' },
                    { validator: validateNumver, message: '请填写奖励积分2', trigger: 'blur' }
                ],
                award_money: [
                    { required: true, message: '请填写奖励金额', trigger: 'blur' },
                    { validator: validateNumver, message: '请填写奖励金额', trigger: 'blur' }
                ],
                award_score_for_level: [
                    { validator: validateAwardScoreLevel, trigger: 'blur' }
                ],
                award_money_for_level: [
                    { validator: validateAwardMoneyLevel, trigger: 'blur' }
                ],
                statistic: [
                    { validator: validateStatistic, trigger: 'blur' }
                ],
                submit_config: [
                    { validator: validateSubmitConfig, trigger: 'blur' }
                ],
            },
            submitting: false,
            init: false,

            baseUrl: '',
            mobileUrl: '',
            sessionTicket: localStorage.getItem('sessionTicket'),
            escape: escape,
        };
    },
    created() {
        this.authResult = this.$route.meta.authResult;
        this.$store.commit('SET_HEADER', this.breadcrumbList);

        this.taskNo = this.$route.query.task_no ? this.$route.query.task_no : '';

        this.fnGetSimpleTasks();

        if (this.taskNo) {
            this.baseUrl = this.$baseUrl;
            this.mobileUrl = location.host == 'phaadmin.wxhand.com' ? 'http://class.zsdx.cn' : 'http://task.wxhand.com';
            // TODO baseURl
            this.previewUrl = '';
            this.fnGetTask();
        }else{
            this.init = true;
        }
    },
    methods: {
        /** 获取任务 */
        fnGetTask() {
            this.$post('/task/task%5Cget', {
                task_no: this.taskNo
            }, resp => {
                if(resp.code == 1){
                    let tmp = resp.data;

                    // 初始化时间
                    tmp.taskTime = [new Date(tmp.start_time * 1000), new Date(tmp.end_time * 1000)];
                    // 初始化奖励类型;
                    if(Object.keys(tmp.award_score_for_level).length > 0){
                        tmp.award = [2, 2];
                        this.awardScoreLevel = tmp.award_score_for_level;
                        tmp.award_score_for_level.lv0 = tmp.award_score;
                    }else if(Object.keys(tmp.award_money_for_level).length > 0){
                        tmp.award = [2, 1];
                        tmp.award_money_for_level.lv0 = tmp.award_money;
                        this.awardMoneyLevel = tmp.award_money_for_level;
                    }else if(tmp.award_score > 0){
                        tmp.award = [1, 2];
                    }else if(tmp.award_money){
                        tmp.award = [1, 1];
                    }else{
                        tmp.award = [1, 1];
                    }
                    // 初始化统计表单
                    tmp.statistic = tmp.statistic_config.length > 0 ? 1 : 2;
                    if(tmp.statistic == 1){
                        this.statisticSize = tmp.statistic_config.length;
                    }
                    // 初始化文本提交
                    tmp.texts_help = tmp.submit_config.submit_texts_help.length > 0;
                    if(tmp.texts_help){
                        this.textsHelpSize = tmp.submit_config.submit_texts_help.length;
                    }else{
                        this.textsHelpSize = 1;
                        tmp.submit_config.submit_texts_help = [{
                            desc: ''
                        }];
                    }
                    // 初始化图片列表提交
                    tmp.images_help = tmp.submit_config.submit_images_help.length > 0;
                    if(tmp.images_help){
                        this.imagesHelpSize = tmp.submit_config.submit_images_help.length;
                        for(var i in tmp.submit_config.submit_images_help){
                            tmp.submit_config.submit_images_help[i].preview_url = tmp.submit_config.submit_images_help[i].img_url;
                            tmp.submit_config.submit_images_help[i].status = 'success';
                        }

                    }else{
                        this.imagesHelpSize = 1;
                        tmp.submit_config.submit_images_help = [{
                            status: 'success',
                            preview_url: '',
                            "img_url": "",
                            "desc": ""
                        }];
                    }

                    this.formData = tmp;
                    console.log(this.formData);
                    this.init = true;
                }else{
                    this.$message({
                        type: 'warning',
                        center: true,
                        message: resp.msg
                    });
                }
            });
        },
        fnSubmit(){
            if(this.submitting){
                return ;
            }
            this.formData.intro = this.$refs.ueditor ? this.$refs.ueditor.getUEContent() : '';
            this.$refs.mainform.validate(valid => {
                if(valid){
                    this.submitting = true;

                    let data = {
                        hire_name: this.formData.hire_name,
                        hire_logo: this.formData.hire_logo,
                        monitor_say_content: this.formData.monitor_say_content,
                        image_url: this.formData.image_url,
                        class_limit: this.formData.class_limit,
                        title: this.formData.title,
                        type: this.formData.type,
                        category: this.formData.category,
                        all_count : this.formData.all_count,
                        start_time: Date.parse(this.formData.taskTime[0])/1000,
                        end_time : Date.parse(this.formData.taskTime[1])/1000,
                        intro: this.formData.intro,
                        level_limit: this.formData.level_limit,
                        pre_task_nos: JSON.stringify(this.formData.pre_task_nos),
                        can_get_lottery_try_count:this.formData.can_get_lottery_try_count,
                        award_score: 0,
                        award_money: 0,
                        award_score_for_level: '[]',
                        award_money_for_level: '[]',
                        statistic_config: '[]',
                        submit_texts_help: '[]',
                        submit_images_help: '[]'
                    };

                    if(this.formData.award[0] == 1 && this.formData.award[1] == 1){
                        data.award_money = this.formData.award_money;
                    }else if(this.formData.award[0] == 1 && this.formData.award[1] == 2){
                        data.award_score = this.formData.award_score;
                    }else if(this.formData.award[0] == 2 && this.formData.award[1] == 1){
                        data.award_money_for_level = JSON.stringify(this.awardMoneyLevel);
                    }else if(this.formData.award[0] == 2 && this.formData.award[1] == 2){
                        data.award_score_for_level = JSON.stringify(this.awardScoreLevel);
                    }

                    if(this.formData.statistic == 1){
                        data.statistic_config = JSON.stringify(this.formData.statistic_config);
                    }

                    if(this.formData.texts_help){
                        data.submit_texts_help = JSON.stringify(this.formData.submit_config.submit_texts_help);
                    }
                    if(this.formData.images_help){
                        let imgs = [];

                        for(var i in this.formData.submit_config.submit_images_help){
                            imgs.push({
                                img: this.formData.submit_config.submit_images_help[i].img_url,
                                desc: this.formData.submit_config.submit_images_help[i].desc
                            });
                        }
                        data.submit_images_help = JSON.stringify(imgs);
                    }

                    if(this.taskNo){
                        data.task_no = this.taskNo;

                        this.$post('/task/task%5Cedit', data, resp => {
                            if(resp.code == 1){
                                this.$message({
                                    type: 'success',
                                    center: true,
                                    message: '修改成功'
                                });
                                this.fnGetTask();
                                this.$refs.mainform.resetFields();
                            }else{
                                this.$message({
                                    type: 'warning',
                                    center: true,
                                    message: resp.msg
                                });
                            }
                            this.submitting = false;
                        });
                    }else{
                        this.$post('/task/task%5Cadd', data, resp => {
                            if(resp.code == 1){
                                this.taskNo = resp.data.task_no;
                                this.$message({
                                    type: 'success',
                                    center: true,
                                    message: '新增成功'
                                });
                                this.$router.push({
                                    name: 'TaskList'
                                });
                            }else{
                                this.$message({
                                    type: 'warning',
                                    center: true,
                                    message: resp.msg
                                });
                            }
                            this.submitting = false;
                        });
                    }

                }
            });
        },
        /** 预览 */
        fnShowPreview() { },
        fnGetSimpleTasks() {
            this.$post('/task/task%5Cget_simple_list', {}, resp => {
                if (resp.code == 1) {
                    this.preTaskList = resp.data.list;
                }
            });
        },
        /** 奖励方式改变 */
        fnAwardChange(val) {
            if(this.formData.award[0] == 1 && this.formData.award[1] == 1){
                if(!this.formData.award_money)
                    this.formData.award_money = this.awardMoneyLevel.lv0;
            }else if(this.formData.award[0] == 1 && this.formData.award[1] == 2){
                if(!this.formData.award_score)
                    this.formData.award_score = this.awardScoreLevel.lv0;
            }else if(this.formData.award[0] == 2 && this.formData.award[1] == 1){
                if(!this.awardMoneyLevel.lv0)
                    this.awardMoneyLevel.lv0 = this.formData.award_score;
            }else if(this.formData.award[0] == 2 && this.formData.award[1] == 2){
                if(!this.awardScoreLevel.lv0)
                    this.awardScoreLevel.lv0 = this.formData.award_score;
            }
        },
        fnChangeItem(total, list, item) {
            let resList = list;

            if (list.length > total) {
                resList.splice(total, list.length-total);
            } else if (list.length < total) {
                for (var i = list.length; i < total; i++) {
                    resList.push(Object.assign({} , item));
                }
            }
        },
        /** 数组中删除某个元素 */
        fndeleteItem(list, index, bind) {
            list.splice(index, 1);
            this[bind] = list.length;
        },
        /** 上传组件回调 文件队列修改 */
        fnUploadChange(file, item) {
            item.preview_url = file.url;
        },
        fnBeforeUpload(file, item){
            item.status = 'uploading';
        },
        /** 上传组件回调 上传成功 */
        fnUploadSuccess(resp, file, item) {
            item.img_url = resp.url;
            item.status = 'success';
        },
        fnUploadError(item){
            item.preview_url = '';
            item.status = 'fail';
        },
        fnUpload(e, item) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();

            pic.append('file', e.file);
            item.uploadTime = timeTmp;
            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                progress: e.onProgress,
                success: resp => {
                    if(item.uploadTime != timeTmp){
                        return ;
                    }
                    if (resp.code == 1) {
                        // 调用组件成功回调,修改样式
                        e.onSuccess(resp.data, {
                            url: resp.data.url
                        }, this.fileList);
                    } else {
                        // 失败后调用组件error回调,删除对应元素
                        e.onError(resp.msg);
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                    }
                }
            });
        },
        fnUploadImage(e, success, error) {
            let timeTmp = new Date().getTime();
            let pic = new FormData();

            pic.append('file', e.file);
            this.$upload({
                url: '/__local/common%5Cupload',
                data: pic,
                success: resp => {
                    if (resp.code == 1) {
                        success(resp);
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '上传图片失败',
                            center: true
                        });
                        error(resp);
                    }
                }
            });
        },
        fnUploadImageOfTask(e){
            this.fnUploadImage(e, (resp) => {
                this.formData.image_url = resp.data.url;
            }, (resp) => {
                console.log(resp.msg);
            });
        },
        fnUploadImageOfCustomerLogo(e) {
            this.fnUploadImage(e, (resp) => {
                this.formData.hire_logo = resp.data.url;
            }, (resp) => {
                console.log(resp.msg);
            });
        },
        fnReset(){

        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        }
    },
};
</script>

<style lang="less" scoped>
    .margin-top{
        margin-top: 15px;
    }
    .task-editor-wrap {
      background: #fff;
      margin: 15px;
      margin-bottom: 0;
      padding: 30px;
      overflow: auto;
    }
    .form-unit {
      margin-bottom: 40px;
    }
    .form-title {
      font-size: 16px;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.85);
      line-height: 18px;
      padding: 0 10px;
      border-left: 2px solid #1890ff;
      margin-bottom: 20px;
    }
    .task-input {
      width: 435px !important;
    }
    .task-intro-input {
      width: 750px;
    }
    .table-inner-input {
      outline: none;
      line-height: 20px;
      font-size: 14px;
      width: 100%;
      background: transparent;
      text-align: center;
      cursor: pointer;
    }
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
      -webkit-appearance: none;
    }
    input[type="number"] {
      -moz-appearance: textfield;
    }
    .input-width-delete {
      margin-top: 15px;
      font-size: 0;
      .task-input{
          margin-right: 10px;
      }
    }

    .operate-baar {
      width: 100%;
      text-align: center;
      margin-top: 168px;
    }
    .preview-image {
      width: 120px;
      height: 120px;
      background-position: center;
      background-size: contain;
      background-repeat: no-repeat;
    }

    .pic-width-delete {
      margin-top: 15px;
      float: left;
      margin-right:60px;
      display: inline-block;
      width: 500px;
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      .pic-unit {
        flex: 1;
        margin-right: 10px;
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        padding: 15px;
        border-radius: 4px;
        border: 1px solid rgba(217, 217, 217, 1);
        &-index {
          width: 28px;
          height: 28px;
          background: rgba(243, 250, 255, 1);
          border: 1px solid rgba(24, 144, 255, 1);
          margin-right: 15px;
          border-radius: 28px;
          text-align: center;
          line-height: 28px;
          color: rgba(24, 144, 255, 1);
        }
        &-detail{
            flex: 1;
        }
        &-desc{
            width:100%;
        }
        &-textarea{
            resize: none;
            width: 100%;
            height: 44px;
            line-height: 20px;
            border: 0;
            outline: 0;
        }
        .pic-value {
          width:100%;
          height: 215px;
          background-position: center;
          background-size: contain;
          background-repeat: no-repeat;
          background-color: #F6F6F6;
          position: relative;
          .loading{
              width:100%;
              height: 100%;
              line-height: 215px;
              background: rgba(0,0,0,.3);
              transition: opacity .3s ease-in-out;
          }
          .tip{
              font-size: 14px;
              color: #fff;
              line-height: 215px;
              width: 100%;
              height:100%;
              background: rgba(0,0,0,.5);
              position: absolute;
              left: 0;
              top: 0;
              opacity: 0;
              transition: opacity .3s ease-in-out;
          }
          &:hover{
              .loading{
                  opacity: 0;
              }
              .tip{
                  opacity: 1;
              }
          }
        }
        .pic-empty-container{
            display: flex;
            width: 100%;
            height: 100%;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        .pic-empty-plus{
            font-size:24px;
            width: 24px;
            line-height: 24px !important;
            color: rgba(0,0,0,.45);
        }
        .pic-empty-desc{
            font-size:14px;
            color:rgba(0,0,0,0.65);
            line-height:22px;
        }
      }
    }
    .upload-list{
        margin-top:10px;
    }
    .editor-wrap{
        position: relative;
    }
    .uploaded-image{
        width: 360px;
        height: 180px;
        background-size: 100%;
        background-position: center center;
        background-repeat: no-repeat;
        &:hover{
            .icon-delete{
                display: inline-block;
            }
        }
        .icon-delete{
            margin-top: 90px;
            transform: translateY(-50%);
            display: none;
        }
    }
</style>
<style lang="less">
    .task-intro-input {
      .ql-toolbar {
        border-radius: 4px 4px 0 0;
      }
      .ql-container {
        border-radius: 0 0 4px 4px;
      }
      .ql-toolbar.ql-show,
      .ql-container.ql-snow {
        border-color: #c0c4cc !important;
      }
    }
    .pic-unit-img{
        .el-upload--picture-card {
            border: 0;
            background-color: transparent;
            width: 100%;
            height: 100%;
        }
    }
    .avatar-uploader-customer{
        display: inline-block;
        .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        .el-upload:hover {
            border-color: #409EFF;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 100px;
            height: 100px;
            line-height: 100px;
            text-align: center;
        }
        .avatar {
            width: 100px;
            height: 100px;
            display: block;
        }
    }
</style>
